package IO_.homework;

import java.io.*;
import java.util.Scanner;

/**
 * 扫描指定目录，并找到名称或者内容中包含指定字符的所有普通文件（不包含目录）
 */
public class test3 {
    public static void main(String[] args) {
        System.out.println("原目录:");
        Scanner scan=new Scanner(System.in);
        String src=scan.next();
        File file1 = new File(src);
        if(!file1.isDirectory()){
            System.out.println("目录有错误!");
            return;
        }
        System.out.println("请输入要查找的内容:");
        String s=scan.next();
        Scan(file1,s);
    }

    private static void Scan(File file1, String s) {
        File[] files = file1.listFiles();
        if(files==null){
            return;
        }
        for(File f:files){
            if(f.isFile()){
                //对文件进行扫描
                ScanFile(f,s);
            }else if(f.isDirectory()){
                Scan(f,s);
            }else{
                ;
            }
        }
    }

    private static void ScanFile(File f, String s) {
        try(InputStream inputStream=new FileInputStream(f)){
            StringBuilder stringBuilder = new StringBuilder();
            while(true){
                byte[] buffer=new byte[1024];
                int n = inputStream.read(buffer);
                if(n==-1){
                    break;
                }
                String str=new String(buffer,0,n);
                stringBuilder.append(str);
            }
            if(stringBuilder.indexOf(s)!=-1){
                System.out.println("找到了,路径为: "+f.getAbsolutePath());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
